package com.king.headline.UI;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.king.headline.R;
import com.king.headline.base.BaseActivity;
import com.king.headline.beans.UserInfo;
import com.king.headline.cache.CacheUtils;
import com.king.headline.net.Callback;
import com.king.headline.net.NetWork;
import com.king.headline.util.AccountManager;
import com.king.headline.util.CustomToast;
import com.king.headline.util.KeyBoardUtils;
import com.king.headline.util.UIUtils;
import com.king.headline.util.Utils;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 手机号快捷登录界面
 *
 * @author king
 */
public class LogingPromoteActivity extends BaseActivity implements OnClickListener {
    private TextView tv_title;//标题
    private EditText et_userName;//手机号
    private TextView bt_getPassWord;//动态获取密码
    private EditText et_password;//密码
    private Button bt_loging;
    private ProgressDialog pDialog;
    private TimerTask task;
    private int TIME = 0x852147;
    private int time = 60;//60秒
    private long timeQuite = 0;

    private Boolean firstTimeClick = true;//是否是首次点击获取
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == TIME) {
                time--;
                if (time <= 0) {
                    bt_getPassWord.setClickable(true);
                    bt_getPassWord.setText("获取验证码");
                } else {
                    bt_getPassWord.setText(String.valueOf(time) + "秒后再试");
                }
            }
        }

        ;
    };
    private EditText et_pwd1;
    private Timer timer;
    private String preActivityName;
    private boolean canback;
    private ImageView iv_qq;
    private ImageView iv_sina;
    private ImageView iv_weichat;
    private TextView tv_regist;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UIUtils.addActivity(this);
        baseSetContentView(R.layout.activity_loging_promote);
        canback = getIntent().getBooleanExtra("canback",false);

        initView();

        task = new TimerTask() {

            @Override
            public void run() {
                handler.sendEmptyMessage(TIME);
            }
        };
    }


    private void initView() {
        setBackIcon(false);
        iv_qq = (ImageView) findViewById(R.id.iv_qq);
        iv_sina = (ImageView) findViewById(R.id.iv_sina);
        iv_weichat = (ImageView) findViewById(R.id.iv_weichat);
        tv_title = (TextView) findViewById(R.id.tv_title);
        et_userName = (EditText) findViewById(R.id.et_userName);
        bt_getPassWord = (TextView) findViewById(R.id.bt_getPassWord);
        TextView tv_login_type2 = (TextView) findViewById(R.id.tv_login_type2);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_loging = (Button) findViewById(R.id.bt_loging);
        tv_regist = (TextView) findViewById(R.id.tv_regist);
        tv_title.setText("手机号快捷登录");
        bt_getPassWord.setOnClickListener(this);
        bt_loging.setOnClickListener(this);
        tv_login_type2.setOnClickListener(this);
        if (canback){
            setBackIcon(true);
        }else{
            setBackIcon(false);
        }
        iv_qq.setOnClickListener(this);
        iv_sina.setOnClickListener(this);
        iv_weichat.setOnClickListener(this);
        tv_regist.setOnClickListener(this);

    }

    private void getCodeTak(String phone) {
        pDialog = ProgressDialog.show(LogingPromoteActivity.this, "", "请稍候~");
        NetWork.getInstance().getCode(phone, new Callback() {
            @Override
            public void success(String result) {
                Utils.dismissDialog(pDialog);
                timer = new Timer();
                time = 60;
                if (firstTimeClick) {
                    firstTimeClick = false;
                    timer.schedule(LogingPromoteActivity.this.task, 0, 1000);
                }
                bt_getPassWord.setClickable(false);
                et_password.requestFocus();
                et_password.isFocused();
                CustomToast.showToast("验证码已发送到您手机上~");
            }

            @Override
            public void notice(JSONObject jsonObject, String message) {
                Utils.dismissDialog(pDialog);
                CustomToast.showToast(message);
                bt_getPassWord.setClickable(true);
                bt_getPassWord.setText("获取验证码");
            }

            @Override
            public void failed(String e) {
                Utils.dismissDialog(pDialog);
                CustomToast.showToast(e);
                bt_getPassWord.setClickable(true);
                bt_getPassWord.setText("获取验证码");
            }
        });
    }

    private void loging(String phone, String code) {
        pDialog = ProgressDialog.show(LogingPromoteActivity.this, "", "请稍候~");
        NetWork.getInstance().loginByPromote(phone, code, new Callback() {
            @Override
            public void success(String result) {
                Gson gson = new Gson();
                UserInfo userInfo = gson.fromJson(result, UserInfo.class);
                AccountManager.getInstance().setUser(userInfo);
                CacheUtils.putString(CacheUtils.APIKEY, userInfo.apikey);
                startActivity(new Intent(LogingPromoteActivity.this, MainUI.class));
                LogingPromoteActivity.this.finish();
            }

            @Override
            public void notice(JSONObject jsonObject, String message) {
                Utils.dismissDialog(pDialog);
                CustomToast.showToast(message);
            }

            @Override
            public void failed(String e) {
                Utils.dismissDialog(pDialog);
                CustomToast.showToast(e);
            }
        });


    }

    @Override
    public void onClick(View v) {
        String phone = et_userName.getText().toString().trim();
        switch (v.getId()) {
            case R.id.bt_getPassWord:
                if (Utils.isPhoneNumberValid(phone)) {

                    getCodeTak(phone);


                } else {
                    CustomToast.showToast("手机号码输入有误");
                }

                break;
            case R.id.bt_loging:
                String phone2 = et_userName.getText().toString().trim();
                String code = et_password.getText().toString().trim();

                //隐藏键盘
                KeyBoardUtils.closeKeybord(et_userName);
                if (!Utils.isPhoneNumberValid(phone2)) {

                    CustomToast.showToast("手机号码输入有误");
                    return;
                }
                if (TextUtils.isEmpty(code)) {

                    CustomToast.showToast("验证码不能为空");
                    return;
                }
                loging(phone2, code);
                break;
            case R.id.tv_login_type2:
                Intent intent = new Intent( UIUtils.getContext(), Loging2Activity.class);
                startActivity(intent);
                break;
            case R.id.iv_qq:
                break;
            case R.id.iv_sina:
                CustomToast.showToast("暂未开放");
//                loginThree(SHARE_MEDIA.SINA);
                break;
            case R.id.iv_weichat:
                CustomToast.showToast("暂未开放");

                break;
            case R.id.tv_regist:
                startActivity(new Intent(this, RegistActivity.class));
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        UIUtils.removeActivity(this);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (canback){
                finish();
            }else {
                if (System.currentTimeMillis() - timeQuite < 2000) {// 点击2次的时间小于2秒，退出程序
                    UIUtils.finishAll();
                } else {
                    timeQuite = System.currentTimeMillis();
                    CustomToast.showToast("再点一次退出程序！");
                }
            }
            return true;

        }

        return super.onKeyDown(keyCode, event);
    }


}
